package com.yx.filesystem.storage;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;

public class FileSetHandler extends SocketHandler {

	public FileSetHandler() {
		// TODO 自动生成的构造函数存根
	}

	@Override
	public boolean handler(BufferedInputStream socketInput,
			BufferedOutputStream socketOutput, Transport transport)
			throws Exception {
		if(SpaceChecker.isSpaceFull())throw new Exception("Storage space used more than 85%,Storage space is full!");
		Archive fileDoc = null;
		String fileName=transport.getMessage();
		if (transport.getStatus()) {
			fileDoc = new Archive(fileName);
		} else {
			fileDoc = createMyOwnNodeArchive();
			fileName=fileDoc.getName();
		}
		long fileLength=transport.getJsonContent().getLong("FILE_LENGTH");
		fileDoc.write(socketInput,fileLength);
		Transport returnTransport = new Transport(null, true,fileName, null);
		returnTransport.write(socketOutput);
		Server.get().setStorageSaveState(fileDoc.getNodeId()[0], fileDoc.getFileTotalNumber());
		if(!transport.getStatus()){
			Server.get().getBackupDaemonService().awakeDaemon();
		}		
		return true;
	}
	public static final Archive createMyOwnNodeArchive() throws Exception {
		Server server=Server.get();	
		return new Archive(server.getServerNode(),Archive.NOW_TIME_STAMP,FileCounter.nextFileNumber());
	}

}
